<?php

namespace App\Services\User;

use App\Enums\CurStatusEnums;
use App\Enums\ResponseCode;
use App\Exceptions\BusinessException;
use App\Helpers\ValidatorTool;
use App\Models\User;
use App\Services\AbstractBaseService;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class UserService extends AbstractBaseService
{

    /**
     * 创建用户
     * @param string $mobile 手机号码或者邮箱
     * @return void
     * @throws BusinessException
     */
    public static function createUser(string $mobile): void
    {
//        //判断用户输入的是否是邮箱或者手机号码
        if (!ValidatorTool::is_mobilePhone($mobile)) {
            self::exception(ResponseCode::VALIDATION_ERROR, trans("请输入手机号码"));
        }
        $lockKey = 'user-register-account:' . $mobile;
        $lock = Cache::lock($lockKey, 5);
        if ($lock->get()) {
            DB::beginTransaction();
            try {
                $data = [
                    'mobile' => $mobile,
                    'gender' => 0,
                    'avatar_url' => "",
                    'is_lock' => CurStatusEnums::STATUS_INVALID,
                ];
                User::query()->create($data);
                DB::commit();
                // 推送耗时任务到队列
            } catch (QueryException $exception) {
                DB::rollBack();
                self::exception(ResponseCode::SERVICE_UNAVAILABLE, config('app.debug') ? $exception->getMessage() : trans('注册数据异常退出'));
            } finally {
                $lock->release();
            }
        } else {
            self::exception(ResponseCode::LOCKED, trans('帐号正在注册中请勿重复提交'));
        }
    }

    /**
     * 修改会员资料
     * @param int $UserId
     * @param array $info
     */
    public static function editPayProfile(int $UserId, array $info)
    {
        $infoKey = ['name', 'gender', 'birthday', 'identity', 'mobile', 'avatar_url','self_description'];
        $upDate = [];
        foreach ($infoKey as $item) {
            if (!empty($info[$item])) {
                $upDate[$item] = $info[$item];
            }
        }
        if (!empty($info['gender']) && in_array($info['gender'], [0, 1, 2])) {
            $upDate['gender'] = $info['gender'];
        }
        !empty($upDate) && User::where('id', '=', $UserId)->update($upDate);
    }
}
